import pandas as pd
from typing import Dict

from interfaces.transformers import IPivotMetrics
from constants import DATA_FESTIVAL, MERGE_KEYS, BASE_COLS
from common.pivot.default_period_pivot import PeriodPivotHelper


class PivotMetricsTransformer(IPivotMetrics):
    def __init__(self, default_source_data: str):
        self.default_source_data = default_source_data
        self.helper = PeriodPivotHelper(default_source_data)

    def verify_key_metrics(self, config: Dict) -> pd.DataFrame:
        sheet_name = config['sheet_name']
        base_cols = config['base_cols']
        period_conditions = config['period_conditions']
        merge_keys = config['merge_keys']

        # 读取以解析筛选/出组的真实标签值
        df = pd.read_excel(self.default_source_data, sheet_name=sheet_name, dtype=str, keep_default_na=False, na_values=[])
        df.columns = [str(c).strip() for c in df.columns]
        df = df.loc[:, ~df.columns.duplicated()]

        screening_mask = period_conditions['screening'](df)
        outgroup_mask = period_conditions['outgroup'](df)
        screening_values = df.loc[screening_mask, DATA_FESTIVAL].unique().tolist()
        outgroup_values = df.loc[outgroup_mask, DATA_FESTIVAL].unique().tolist()
        if not screening_values or not outgroup_values:
            return pd.DataFrame()
        screening_label = screening_values[0]
        outgroup_label = outgroup_values[0]

        result = self.helper.build(
            sheet_name=sheet_name,
            base_cols=base_cols,
            merge_keys=merge_keys,
            period_column=DATA_FESTIVAL,
            screening_value=screening_label,
            outgroup_value=outgroup_label,
            screening_prefix=screening_label,
            outgroup_prefix=outgroup_label,
            expand_after_line_number=True,
        )
        return result